package com.szbber.commen.api

import android.content.Context
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.szbber.commen.dialog.LoadingDialog
import com.szbber.medical.commen.R
import kotlinx.coroutines.CoroutineExceptionHandler
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.launch


private var loadingDialog: LoadingDialog? = null

fun showLoadingDialog(context: Context?) {
    dismissLoadingDialog()
    val builder: LoadingDialog.Builder =
        LoadingDialog.Builder(context)
            .setMessage(context?.getString(R.string.common_loading))
            .setCancelable(true)
    loadingDialog = builder.create()
    loadingDialog?.show()
}

fun dismissLoadingDialog() {
    if (null != loadingDialog && loadingDialog!!.isShowing) {
        loadingDialog?.dismiss()
        loadingDialog = null
    }
}

/**
 * ViewModel扩展方法：启动协程
 * @param block 协程逻辑
 * @param onError 错误回调方法
 * @param onComplete 完成回调方法
 */

fun ViewModel.launch(
    context: Context?,
    block: suspend CoroutineScope.() -> Unit,
    onError: (e: Throwable) -> Unit = {},
    onComplete: () -> Unit = {}
) {
    viewModelScope.launch(
        CoroutineExceptionHandler { _, throwable ->
            run {
                // 统一处理错误
                ExceptionUtil.catchException(throwable)
                dismissLoadingDialog()
                onError(throwable)
            }
        }
    ) {
        try {
            showLoadingDialog(context)
            block.invoke(this)
        } finally {
            dismissLoadingDialog()
            onComplete()
        }
    }
}


fun ViewModel.launch(
    block: suspend CoroutineScope.() -> Unit,
) {
    viewModelScope.launch{
        block.invoke(this)
    }
}
